<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\ApiController;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use App\Models\Category;
use Validator;

class CategoryController extends ApiController
{
    /**
     * 分类类别
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        return $this->success($category = Category::get()->toTree());
    }

    /**
     * 获取制定分类信息
     */
    public function show($id) {
        return $this->success(Category::select('id', 'name', 'parent_id')->find($id));
    }

    /**
     * 创建分类
     */
    public function store(Request $request)
    {
        $parent_id = $request->input('parent');
        $name = $request->input('name');
        
        $messages = [
            'name.required' => '分类名称不能为空',
            'name.max' => '长度不超过50个字符',
            'parent.exists' => '父级分类不存在'
        ];

        $validator = Validator::make($request->all(), [
            'name' => 'required|max:50',
            'parent' => 'nullable|exists:categorys,id'
            
        ], $messages);

        if ($validator->fails()) {
            return $this->failed($validator->errors()->first());
        }

        $parent = Category::find($parent_id);
        if(Category::create(['name' => $name], $parent)) {
            $this->success('添加成功');
        }
    }

    /**
     * 更新分类
     */
    public function update(Request $request, $id) {
        $parent_id = $request->input('parent');
        $name = $request->input('name');

        $messages = [
            'name.required' => '分类名称不能为空',
            'name.max' => '长度不超过50个字符',
            'parent.exists' => '父级分类不存在'
        ];

        $validator = Validator::make($request->all(), [
            'name' => 'required|max:50',
            'parent' => 'nullable|exists:categorys,id'
            
        ], $messages);

        if ($validator->fails()) {
            return $this->failed($validator->errors()->first());
        }

        $category = Category::find($id);
        $category->name = $name;

        if($parent_id) {
            $category->appendToNode($parent)->save();
        }else {
            $category->makeRoot()->save(); // 设置为根节点
        }
        
        return $this->success('更新成功');
    }
}
